﻿using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace DefaultNamespace
{
    public  class CreateABCompare
    {
        [MenuItem("AB包工具/创建对比文件")]
        public static void CreateABCompareFile()
        {
            DirectoryInfo directory = Directory.CreateDirectory(Application.dataPath + "/ArtRes/AB/PC/");
            FileInfo[] fileInfos = directory.GetFiles();

            //用于存储信息的 字符串
            string abCompareInfo = "";
            foreach (var fileInfo in fileInfos)
            {
                if (fileInfo.Extension == "")
                {
                    abCompareInfo += fileInfo.Name + " " + fileInfo.Length + " " + GetMD5(fileInfo.FullName);
                    //用一个分隔符分开不同文件之间的信息
                    abCompareInfo += '|';
                }
            }

            abCompareInfo = abCompareInfo.Substring(0, abCompareInfo.Length - 1);
            File.WriteAllText(Application.dataPath + "/ArtRes/AB/PC/ABCompareInfo.txt", abCompareInfo);
            //刷新编辑器
            AssetDatabase.Refresh();
            Debug.Log("AB包对比文件生成成功");
        }
        public static string GetMD5(string filePath)
        {
            //将文件以流的形式打开
            using (FileStream file = new FileStream(filePath, FileMode.Open))
            {
                //声明一个MD5对象 用于生成MD5码
                MD5 md5 = new MD5CryptoServiceProvider();
                //利用API 得到数据的MD5码 16个字节 数组
                byte[] md5Info = md5.ComputeHash(file);

                //关闭文件流
                file.Close();

                //把16个字节转换为 16进制 拼接成字符串 为了减小md5码的长度
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < md5Info.Length; i++)
                    sb.Append(md5Info[i].ToString("x2"));

                return sb.ToString();
            }
        }
    }
}